package com.fast.alden.portal.util;

import com.fast.alden.data.model.PortalUser;
import com.fast.alden.portal.security.model.PortalUserDetailsImpl;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;

import java.util.Optional;

public class PortalSecurityUtils {
    public static PortalUser getCurrentUser() {
        return Optional.ofNullable(SecurityContextHolder.getContext())
                .map(SecurityContext::getAuthentication)
                .filter(Authentication::isAuthenticated)
                .filter(authentication -> !(authentication instanceof AnonymousAuthenticationToken))
                .map(Authentication::getPrincipal)
                .map(PortalUserDetailsImpl.class::cast)
                .map(PortalUserDetailsImpl::getUser)
                .map(PortalUser.class::cast)
                .orElse(null);
    }
}
